﻿using System;
using Newtonsoft.Json.Linq;
using WebAPI.Utils.wechat;

namespace WebAPI.Utils
{
    internal class Wechat
    {
        private string host = "https://api.weixin.qq.com";

        private string appId;

        private string appSecret;

        private string access_token;
        
        public Wechat(string appId, string appSecret)
        {
            access_token = SetToken(appId, appSecret);
        }

        public string GetToken()
        {
            return access_token;
        }

        // 获取access_token
        private string SetToken(string appId, string appSecret)
        {
            string fileName = "access_token.json";
            string str = Token.Read(fileName);
            JObject jObject = JObject.Parse(str);
            long expires_in = Convert.ToInt64(jObject["expires_in"].ToString());
            long time = DateTimeOffset.Now.ToUnixTimeSeconds();
            if (expires_in < time)
            {
                string url = $"{host}/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";
                Client client = new Client();
                string result = client.Get(url);

                // 解析json字符串
                jObject = JObject.Parse(result);

                // 保存json字符串
                Token.Write(fileName, jObject["access_token"].ToString(), Convert.ToInt64(jObject["expires_in"].ToString()) + time);
            }
            return jObject["access_token"].ToString();
        }

        // 生成Scheme
        public string GenerateScheme(string path, string query)
        {
            string url = $"{host}/wxa/generatescheme?access_token={access_token}";
            string bodys = "{\"jump_wxa\":{\"path\":\"" + path + "\",\"query\":\"" + query + "\"}}";
            Client client = new Client();
            string result = client.Post(url, bodys);
            JObject jObject = JObject.Parse(result);
            if (jObject.Property("openlink") != null)
            {
                return jObject["openlink"].ToString();
            }
            return jObject.ToString();
        }

        // 生成Url Link
        public string GenerateUrlLink(string path, string query)
        {
            string url = $"{host}/wxa/generate_urllink?access_token={access_token}";
            string bodys = "{\"path\":\"" + path + "\",\"query\":\"" + query + "\", \"expire_type\":1,\"expire_interval\":1,\"env_version\": \"release\"}";
            Client client = new Client();
            string result = client.Post(url, bodys);
            JObject jObject = JObject.Parse(result);
            if (jObject.Property("openlink") != null)
            {
                return jObject["openlink"].ToString();
            }
            return jObject.ToString();
        }

        public string Code(string code)
        {
            string url = $"{host}/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code";
            Client client = new Client();
            string result = client.Get(url);
            return result;
        }
        
        /**
         * 小程序登录
         * 第一步：wx.login获取 用户临时登录凭证code
         * 第二步：wx.getUserInfo获取加密过的数据encryptedData和解密参数iv
         * 第三步：把步骤一、二中的code、encryptedData、iv传到开发者自己服务端
         * 第四步：服务端获取到code、encryptedData、iv之后用get方法请求微信接口
         * 调用 wx.checkSession 接口检测当前用户登录态是否有效，过期后开可以再调用wx.login获取新的用户登录态。调用成功说明当前未过期，调用失败说明已过期
         *
         * @param code 登录时获取的 code
         */
        public void Authorization(String code) {
            String url = host + "/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
            Client client = new Client();
            var result = client.Get(url);
            var jObject = JObject.Parse(result);
            if (jObject.ContainsKey("errcode")) {
                //this.message = result.getString("errmsg");
            }
            //this.openid = result.getString("openid");
            //this.unionid = result.getString("unionid");
        }
    }
}
